package com.bysc.joinservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.joinservice.entity.JoinRole;
import com.bysc.joinservice.entity.vo.JoinRoleQueryVo;
import com.bysc.joinservice.service.JoinRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/joinservice/join-role")
@Api(tags = "部门角色管理")
public class JoinRoleController {

    @Autowired
    private JoinRoleService joinRoleService;

    @ApiOperation(value = "新增角色（仅限后台）")
    @PostMapping("addRole")
    public Results addRole(@ApiParam(name = "RoleInfo", value = "角色信息", required = true) @RequestBody JoinRole role, HttpServletRequest request) {
        try {
            String TOKEN_clubId= JwtUtils.getClubIdByJwtToken(request);
            if(!StringUtils.isEmpty(TOKEN_clubId)){
                role.setClubId(TOKEN_clubId);
            }
            joinRoleService.save(role);
            return Results.ok().message(MessageConstant.ADD_ROLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.ADD_ROLE_FAIL);
        }
    }

    @ApiOperation(value = "根据id修改角色信息（后台后端要传id）")
    @PutMapping("updateRoleById/{id}")
    public Results updateRoleById(@ApiParam(name = "id", value = "角色id", required = true) @PathVariable String id,
                                  @ApiParam(name = "RoleInfo", value = "修改后的角色信息", required = true) @RequestBody JoinRole updatedRole) {
        try {
            if (updatedRole != null) {
                joinRoleService.updateById(updatedRole);
            }
            return Results.ok().message(MessageConstant.EDIT_ROLE_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_ROLE_FAIL);
        }
    }

    @ApiOperation(value = "根据id删除角色（后台后端要传id）")
    @DeleteMapping("deleteRoleById/{id}")
    public Results deleteRoleById(@ApiParam(name = "id", value = "角色id", required = true) @PathVariable String id) {
        try {
            JoinRole role = joinRoleService.getById(id);
            if (role != null) {
                joinRoleService.removeById(id);
            }
            return Results.ok().message(MessageConstant.DELETE_ROLE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.DELETE_ROLE_FAIL);
        }
    }

    /*
    * 新增分页查询角色
    * 可根据clubId
    * */
    @ApiOperation(value = "分页查询角色（前后台通用）")
    @PostMapping("getRoleByPage/{page}/{limit}")
    public Results getRoleByPage(@ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Long page,
                                 @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable Long limit,
                                 @ApiParam(name = "deptQuery", value = "查询对象", required = false)@RequestBody JoinRoleQueryVo roleQuery, HttpServletRequest request)
    {
        try{
            Page<JoinRole> pageParam = new Page<>(page, limit);
            LambdaQueryWrapper<JoinRole> wrapper = new LambdaQueryWrapper<>();
            if (roleQuery != null) {
                if (!StringUtils.isEmpty(roleQuery.getClubId())) {
                    wrapper.eq(JoinRole::getClubId, roleQuery.getClubId());
                }
                else{
                    String TOKEN_clubId= JwtUtils.getClubIdByJwtToken(request);
                    if(!StringUtils.isEmpty(TOKEN_clubId)){
                        wrapper.eq(JoinRole::getClubId, TOKEN_clubId);
                    }
                }
                if (!StringUtils.isEmpty(roleQuery.getRole())) {
                    wrapper.like(JoinRole::getRole, roleQuery.getRole());
                }
                if (!StringUtils.isEmpty(roleQuery.getId())) {
                    wrapper.eq(JoinRole::getId, roleQuery.getId());
                }
            }
            IPage<JoinRole> pageModel = joinRoleService.page(pageParam, wrapper);
            return Results.ok().data("list",pageModel).message(MessageConstant.QUERY_ROLE_SUCCESS);
        }
        catch (Exception e){
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_ROLE_FAIL);
        }
    }

    @ApiOperation(value = "根据clubId查找所有角色（仅后台）")
    @GetMapping("getRoleByClubId")
    public Results getRoleByClubId(HttpServletRequest request) {
        try {
            String TOKEN_clubId= JwtUtils.getClubIdByJwtToken(request);
            LambdaQueryWrapper<JoinRole> wrapper = new LambdaQueryWrapper<>();
            if(!StringUtils.isEmpty(TOKEN_clubId)){
                wrapper.eq(JoinRole::getClubId, TOKEN_clubId);
            }
            List<JoinRole> roles = joinRoleService.list(wrapper);
            return Results.ok().data("roles", roles).message(MessageConstant.QUERY_ROLE_SUCCESS);
        }
        catch (Exception e){
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_ROLE_FAIL);
        }
    }


//    @ApiOperation(value = "查找所有角色")
//    @GetMapping("getAllRoles")
//    public Results getAllRoles() {
//        try {
//            List<JoinRole> roles = joinRoleService.list(new QueryWrapper<>());
//            return Results.ok().data("roles", roles).message(MessageConstant.QUERY_ROLE_SUCCESS);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_ROLE_FAIL);
//        }
//    }
}